package com.cn.hotel.util;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;


@WebServlet("/code")
public class CodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建空白图片
        BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_3BYTE_BGR);
        //获取图片画笔
        Graphics g = image.getGraphics();
        Random r = new Random();
        //设置画笔颜色
        g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
        //绘制矩形背景
        g.fillRect(0, 0, 80, 20);
        //调用自定义方法
        String number = getNumber(5);
        req.getSession().setAttribute("code", number);
        g.setColor(new Color(0, 0, 0));
        g.setFont(new Font("仿宋", Font.BOLD, 20));
        //设置字体颜色后。绘制    字符串
        g.drawString(number, 5, 15);
        //绘制干扰线
        for (int i = 0; i < 18; i++) {
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
            g.drawLine(r.nextInt(100),
                    r.nextInt(30),
                    r.nextInt(100),
                    r.nextInt(30));
        }
        //将图片强制转换成输出
        resp.setContentType("image/ jpeg");
        OutputStream o = resp.getOutputStream();
        ImageIO.write(image,"jpeg",o);
        o.close();
    }

    private String getNumber(int size) {
        String str = "abcdhtyuiljkFRTGUHIJOKBN";
        StringBuffer number = new StringBuffer();
        Random r = new Random();
        for (int i = 0; i < size; i++) {
            number.append(str.charAt(r.nextInt(str.length())));
        }
        return number.toString();
    }
}
